package cn.tedu.properties.service.impl;

import cn.tedu.exception.ServiceException;
import cn.tedu.properties.constant.AssetConstant;
import cn.tedu.properties.mapper.PropertiesMapper;
import cn.tedu.properties.pojo.dto.PropertiesSaveParam;
import cn.tedu.properties.pojo.entity.Property;
import cn.tedu.properties.pojo.param.QueryParam;
import cn.tedu.properties.pojo.vo.PropertyVO;
import cn.tedu.properties.service.PropertiesService;
import cn.tedu.response.StatusCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PropertiesServiceImpl implements PropertiesService {
    @Autowired
    private PropertiesMapper propertiesMapper;

    //查询全部资产表记录
    @Override
    public List<PropertyVO> selectAll(QueryParam queryParam) {
        //创建QueryMapper对象
        QueryWrapper<Property> queryWrapper = new QueryWrapper<>();
        //添加查询条件,asset_name,asset_category,status
        queryWrapper = setQueryWrapper(queryParam, queryWrapper);
        queryWrapper.select("id","asset_name","asset_code","category_id","asset_category",
                "employee_id","employee_name","brand","status","remark","add_time");//设置查询字段
        log.debug("查询资产表业务入参:queryParam={}", queryParam);
        List<Property> propertyList = propertiesMapper.selectList(queryWrapper);
        PropertyVO propertyVO = new PropertyVO();
        List<PropertyVO> propertyVOList = propertyList.stream().map(p -> {
            try {
                BeanUtils.copyProperties(p, propertyVO);
                return propertyVO;
            } catch (Exception e) {
                log.debug("propertyList转换propertyVOList失败!");
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());
        log.debug("查询资产表业务入参:queryWrapper={},出参:propertyVOList={}", queryWrapper, propertyVOList);
        return propertyVOList;
    }

    //分页查询
    /*@Override
    public IPage<Property> selectPaging(QueryParam queryParam) {
        //创建QueryMapper对象
        QueryWrapper<Property> queryWrapper = new QueryWrapper<>();
        //添加查询条件,asset_name,asset_category,status
        queryWrapper=setQueryWrapper(queryParam,queryWrapper);
        //创建Page对象,param1:当前页,param2:每页条数pageSize
        Page<Property> page = new Page<>(queryParam.getPage(), queryParam.getPageNum());
        log.debug("分页查询资产表业务入参:queryParam={},queryWrapper={},page={}", queryParam, queryWrapper, page);
        page = propertiesMapper.selectPage(page, queryWrapper);
        log.debug("分页查询资产表业务入参:{},出参:propertyPage={}", queryParam, page);
        return page;
    }*/
    @Override
    public IPage<PropertyVO> selectPaging(QueryParam queryParam) {
        //创建QueryMapper对象
        QueryWrapper<Property> queryWrapper = new QueryWrapper<>();
        //添加查询条件,asset_name,asset_category,status
        queryWrapper=setQueryWrapper(queryParam,queryWrapper);
        //创建Page对象,param1:当前页,param2:每页条数pageSize
        Page<PropertyVO> page = new Page<>(queryParam.getPage(), queryParam.getPageNum());
        log.debug("分页查询资产表业务入参:queryParam={},queryWrapper={},page={}", queryParam, queryWrapper, page);
        page = propertiesMapper.selectPage(page, queryWrapper);
        log.debug("分页查询资产表业务入参:{},出参:propertyPage={}", queryParam, page);
        return page;
    }

    //用来给上面queryWrapper添加查询条件
    private QueryWrapper<Property> setQueryWrapper(QueryParam queryParam, QueryWrapper<Property> queryWrapper) {
        queryWrapper.eq(queryParam.getStatus() != null, "status", queryParam.getStatus())
                .like(queryParam.getAssetCategory() != null, "asset_category", queryParam.getAssetCategory())
                .like(queryParam.getAssetName() != null, "asset_name", queryParam.getAssetName());
        log.debug("queryWrapper={}", queryWrapper);
        return queryWrapper;
    }


    /**
     * 对于多个同类型的资产,分别赋予唯一资产编号
     *
     * @param propertiesSaveParam
     */
    @Override
    public void addProperties(PropertiesSaveParam propertiesSaveParam) {
        //判断新增资产的数量
        Integer addNum = propertiesSaveParam.getAddNum();
        if (Objects.equals(null, addNum) || 0 == addNum) {
            log.debug("新增资产数量为0！！！");
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
        ArrayList<Property> list = new ArrayList<>();
        int randomNum = (int) (Math.random() * 10000);//生成一个10000内的随机数
        String paddedNumber = String.format("%06d", randomNum);//随机数补位并且转换成字符串
        //循序给每个Property实例指定编码
        for (int i = 0; i < addNum; i++) {
            Property property = new Property();
            BeanUtils.copyProperties(propertiesSaveParam, property);//复制propertiesSaveParam中的属性
            property.setAssetCode(getAssetUniCode(paddedNumber, i));//设置资产编码assetCode
            property.setCreateTime(LocalDateTime.now());//设置时间
            property.setStatus(AssetConstant.ASSET_STATUS_IN_REPO);//设置状态101 库中
            list.add(property);
        }
        log.debug("新增资产业务入参:propertiesSaveParam={},addNum={}", propertiesSaveParam, addNum);
        int result = propertiesMapper.saveBunch(list);
        log.debug(list.toString());
        log.debug("新增资产业务入参:propertiesSaveParam={},addNum={},成功插入条数:{}", propertiesSaveParam, addNum, result);
    }

    //生成一个资产编码
    private String getAssetUniCode(String paddedNum, int i) {
        StringBuilder sb = new StringBuilder();
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        sb.append(AssetConstant.CODE_PREFIX).append(timeStr).append(paddedNum).append(String.format("%03d", i));//"EMSMKN"+timeStr+paddedNum+i
        return sb.toString();
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void deletePropertiesByIds(Long[] ids) {
        if (ids.length == 0) {
            log.debug("传入参数为null!");
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
        log.debug("删除资产业务入参:ids={}", ids);
        int result = propertiesMapper.deleteBatchIds(Arrays.asList(ids));
        log.debug("删除资产业务入参:ids={},删除成功:{}条", ids,result);
    }

    /**
     * 修改资产信息
     * @param propertiesSaveParam
     */
    @Override
    public void editProperties(PropertiesSaveParam propertiesSaveParam) {
        log.debug("编辑资产业务入参:propertiesSaveParam={}", propertiesSaveParam);
        //创建Property对象
        Property property = new Property();
        //复制propertiesSaveParam属性值到property对象
        BeanUtils.copyProperties(propertiesSaveParam,property);
        //property.setUpdateTime(LocalDateTime.now());//设置更新时间
        int result = propertiesMapper.updateById(property);
        log.debug("编辑资产业务入参:propertiesSaveParam={},数据更新记录:{}条", propertiesSaveParam,result);
    }

    /**
     * 资产报废ById
     * @param id
     */
    @Override
    public void scrapProperties(Long id) {
        log.debug("报废资产业务入参:id={}", id);
        //先判断是否存在该资产
        if(Objects.isNull(propertiesMapper.selectById(id))){
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
        //创建Property对象
        Property property = new Property();
        property.setId(id);//设置资产id
        property.setStatus(AssetConstant.ASSET_STATUS_SCRAPED);//设置资产状态 报废105
        //property.setUpdateTime(new Date());//设置更新时间
        int result = propertiesMapper.updateById(property);
        if (result>0){
            log.debug("Property报废成功!");
        }else {
            log.debug("资产报废失败!");
        }
    }

    /**
     * 批量报废
     * @param ids
     */
    @Override
    public void scrapPropertiesByIds(Long[] ids) {
        log.debug("报废资产业务入参:ids={}", ids);
        //先判断是否存在该资产
        //如果部分存在，部分id不存在?
        //实际上逻辑是错误的,前端传入的批量删除的ID必然是先查询出来返回给前端的
      /*  List<Property> properties = propertiesMapper.selectBatchIds(Arrays.asList(ids));
        if(CollectionUtils.isEmpty(properties)){
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
        //判断资产表中的properties.length<=ids 有部分不存在的资产
        if (properties.size()<ids.length){log.warn("前端传入的id集合中有不存在的资产ID!");}
        //遍历设置
        properties.forEach(p->{
            p.setStatus(AssetConstant.ASSET_STATUS_SCRAPED);//设置资产状态 报废105
            p.setUpdateTime(new Date());//设置更新时间
        });*/
        Property property = new Property();
        property.setStatus(AssetConstant.ASSET_STATUS_SCRAPED);//设置资产状态 报废105
        //property.setUpdateTime(LocalDateTime.now());//设置更新时间
        int result = propertiesMapper.scrapByIds(property,ids);
        if (result>0){
            log.debug("Property批量报废成功!{}条",result);
        }else {
            log.debug("资产报废失败!");
        }
    }

}
